package com.example.service.impl;

import com.example.common.Result;
import com.example.dao.UserDao;
import com.example.pojo.User;
import com.example.service.RedisService;
import com.example.service.UserService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    RedisService redisService;
    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public int add(User user) {
        userDao.add(user);
        return 0;
    }

    @Override
    public void delete(String username) {
        userDao.delete(username);
    }

    @Override
    public User get(String username) {
//        User user = (User) redisTemplate.opsForValue().get(username);
//        if (user != null) {
//            log.info("通过redis查询用户");
//            return user;
//        } else {
//            user = userDao.get(username);
//            redisTemplate.opsForValue().set(username, user);
//            log.info("通过数据库查询用户");
//            return user;
//        }
        return userDao.get(username);

    }

    @Override
    public int update(User user) {
        return userDao.update(user);
    }

    @Override
    public List<User> list() {
        return userDao.list();
    }

    @Override
    public void updateImg(User user) {
        userDao.updateImg(user);

    }

    @Override
    public void updateSignature(User user) {
        userDao.updateSignature(user);
    }

    @Override
    public void updateGender(User user) {
        userDao.updateGender(user);
    }

    @Override
    public User getUserPermission(User user) {
        return userDao.getUserPermission(user);
    }

    @Override
    public void background(User user) {
        userDao.background(user);
    }

    @Override
    public Result generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        try {

            Credential cred = new Credential("AKIDQcdlxwsV1NUgHplRFuRovomW0ECtkT0N", "MZ8VkmbDveASZzVMyshLmyrbhspaBbrn");

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);

            String params = "{\"PhoneNumberSet\":[\"+86" + telephone + "\"],\"TemplateID\":\"665715\",\"Sign\":\"起凡日记\",\"TemplateParamSet\":[\"" + sb.toString() + "\",\"2\"],\"SessionContext\":\"test\",\"SmsSdkAppid\":\"1400399976\"}";
            SendSmsRequest req = SendSmsRequest.fromJsonString(params, SendSmsRequest.class);

            SendSmsResponse resp = client.SendSms(req);

            System.out.println(SendSmsResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }


        redisService.set(REDIS_KEY_PREFIX_AUTH_CODE + telephone, sb.toString());
        redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE + telephone, AUTH_CODE_EXPIRE_SECONDS);

        return Result.SUCCESS(sb.toString() + "获取验证码成功");
    }

    @Override
    public Result verifyAuthCode(String telephone, String authCode) {
        if (StringUtils.isEmpty(authCode)) {
            return Result.FAIL("请输入验证码");
        }
        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        boolean result = authCode.equals(realAuthCode);
        if (result) {
            return Result.SUCCESS("验证码校验成功");
        } else {
            return Result.FAIL("验证码不正确");
        }
    }

}
